import React, { Component } from "react";
import { Form, Input, Select, Space, Button, Modal, Alert, message } from "antd"
import GoBack from "@/components/TheGoBack";
import TheUpload from "@/components/TheUpload";
import TheTable from "@/components/TheTable";
import ThePagination from "@/components/ThePagination";
import "./style.scss";
import { thirdResourceView, thirdChannelPage, thirdResourceEdit, thirdResourceAdd } from "@/request/tripartiteMall/resourceManagement";
const { Option } = Select
const { TextArea } = Input;

export default class Add extends Component {
  constructor(props) {
    super(props)
    this.formRef = React.createRef
    this.state = {
      type: '',
      id: '',
      resourceTypeList: [],
      fileList: [],
      linkTypeList: [],
      linkType: null, // 跳转类型值
      isModalOpen: false,// 跳转频道弹窗
      columns: [
        {
          title: '频道id',
          dataIndex: "channelId",
          key: "channelId",
        },
        {
          title: '频道名称',
          dataIndex: "channelName",
          key: "channelName",
        },
        {
          title: '备注',
          dataIndex: "remark",
          key: "remark",
        },
        {
          title: '创建时间',
          dataIndex: "createTime",
          key: "createTime",
        },
        {
          title: '商品数量',
          dataIndex: "goodsCount",
          key: "goodsCount",
        },
      ],
      dataSource: [],
      selectedRowKeys: [],
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
      total: 1,
      saveFormBtn: false,
      channelId: null
    }
  }
  componentDidMount() {
    const { type, id } = this.props.match.params
    this.setState({ type: type, id: id, }, () => {
      if (id) {
        this.getView(id)
      }
      this.resourceTypeData()
      this.linkTypeData()
    })
  }
  // 资源位详情
  async getView(resourceId) {
    let res = await thirdResourceView({ resourceId })
    if (res.code === 0) {
      this.formRef.setFieldsValue({ ...res.data })
      this.setState({
        fileList: [{
          uid: '-1',
          name: 'image.png',
          url: res.data.resourceImage,
        }],
        linkType: res.data.linkType,
        channelId: res.data.channelId,
        selectedRowKeys: [res.data.channelId]
      })
    }
  }

  // 资源位list数据
  resourceTypeData() {
    this.setState({
      resourceTypeList: [
        { label: "列表首位多图位", value: 3 },
        // { label: "商详页玩法单图位", value: 5 },
      ],
    })
  }
  // 照片上传
  getFileResult(value) {
    if (value.length && value[0] && value[0].response) {
      this.formRef.setFieldsValue({ resourceImage: value[0].response.data });
    } else {
      this.formRef.setFieldsValue({ resourceImage: '' })
    }
  }
  // 跳转类型List数据
  linkTypeData() {
    this.setState({
      linkTypeList: [
        { label: "H5", value: 1 },
        { label: "展示型", value: 2 },
        { label: "频道商品列表", value: 3 },
        { label: "淘宝APP", value: 4 },
        { label: "拼多多APP", value: 5 }
      ]
    })
  }
  // 跳转类型改变
  linkTypeChange = (value) => {
    this.setState({ linkType: value, selectedRowKeys: [] })
    this.formRef.setFieldsValue({ channelName: null, linkUrl: null })
  }
  // 跳转频道
  channelChange = () => {
    this.setState({ isModalOpen: true })
    this.thirdChannelData()
  }
  // 频道列表数据
  async thirdChannelData() {
    let res = await thirdChannelPage({ ...this.state.pageData })
    if (res.code === 0) {
      this.setState({
        dataSource: res.data,
        pageData: { pageNo: res.pageNo, pageSize: res.pageSize },
        total: res.totalCount
      })
    }
  }
  // table选择频道单选
  onChange = (selectedRowKeys, selectedRowKey) => {
    let channelName = selectedRowKey.map(item => { return item.channelName })
    this.formRef.setFieldsValue({ channelName })
    this.setState({ selectedRowKeys: selectedRowKeys })
  }
  // 分页切换
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: { pageNo, pageSize }
    }, () => { this.thirdChannelData() });
  };
  // 保存选择频道
  saveChannel() {
    this.setState({ isModalOpen: false, channelId: this.state.selectedRowKeys.join() })
  }
  // 关闭跳转频道弹窗
  cancelChannel = () => {
    this.setState({ isModalOpen: false });
  }
  // 保存form表单
  onFinish = async (value) => {
    this.setState({ saveFormBtn: true })
    if (value.channelName) {
      delete value.channelName
      if (this.state.channelId === null) {
        delete value.channelId
      } else {
        value.channelId = this.state.channelId
      }
    }
    if (value.linkUrl === null) {
      delete value.linkUrl
    }
    if (this.state.id) {
      let params = { ...value, editFlag: true, resourceId: this.state.id }
      let res = await thirdResourceEdit({ ...params })
      if (res.code === 0) {
        message.success('修改成功！')
        this.props.history.go(-1)
      }
    } else {
      let res = await thirdResourceAdd({ ...value })
      if (res.code === 0) {
        message.success('新建成功！')
        this.props.history.go(-1)
      }
    }
    this.setState({ saveFormBtn: false })
  }
  render() {
    let { type, resourceTypeList, fileList, linkTypeList, linkType, isModalOpen, columns, dataSource, selectedRowKeys, pageData, total, saveFormBtn, channelId } = this.state
    const rowSelection = {
      selectedRowKeys, // 表格选择的Id
      preserveSelectedRowKeys: true,
      type: 'radio',
      onChange: this.onChange
    }
    console.log(rowSelection, "sss");
    return (
      <div className='p-layout-box'>
        <GoBack
          history={this.props.history}
          title={type === 'add' ? "新增资源" : "编辑资源"}
        />
        <div className="p-layout-content" style={{ marginTop: '30px' }}>
          <Form
            name="form"
            labelCol={{ span: 2, }}
            wrapperCol={{ span: 4, }}
            onFinish={this.onFinish}
            ref={ref => this.formRef = ref}
          >
            <Form.Item
              label="所属资源位"
              name="resourceType"
              rules={[{ required: true, message: '所属资源位不能为空' }]}
            >
              <Select placeholder="请选择所属资源位">
                {resourceTypeList.map(item => <Option value={item.value}>{item.label}</Option>)}
              </Select>
            </Form.Item>
            <Form.Item
              label="资源名称"
              name="resourceName"
              rules={[{ required: true, message: '资源名称不能为空' }]}
            >
              <Input placeholder="最多允许输入30个字" maxLength={30} />
            </Form.Item>
            <Form.Item label="上传图片" name="resourceImage" rules={[{ required: true, message: '图片不能为空' }]} extra="支持jpg .jpeg .bmp .png格式,大小不超过5M,最多上传1张">
              <TheUpload getFileResult={(value) => this.getFileResult(value)} maxSize={5} fileList={fileList} len={1} />
            </Form.Item>
            <Form.Item
              label="跳转类型"
              name="linkType"
              rules={[{ required: true, message: '跳转类型不能为空' }]}
            >
              <Select placeholder="请选择跳转类型" onChange={this.linkTypeChange}>
                {linkTypeList.map(item => <Option value={item.value}>{item.label}</Option>)}
              </Select>
            </Form.Item>
            {[1,4,5].includes(linkType)  && <Form.Item
              label="跳转链接"
              name="linkUrl"
              rules={[{ required: true, message: '跳转链接不能为空' }]}
            >
              <Input placeholder="请输入资源跳转链接" />
            </Form.Item>}
            {linkType === 3 && <Form.Item
              label="跳转频道"
              name="channelName"
              rules={[{ required: true, message: '跳转频道不能为空' }]}
            >
              <Input placeholder="请选择跳转频道" onClick={this.channelChange} readOnly />
            </Form.Item>}
            <Form.Item label="备注" name="remark" >
              <TextArea rows={4} placeholder="请输入备注(0-100字)" maxLength={100} />
            </Form.Item>
            <Alert message="保存资源后，资源默认关闭状态，需手动开启" type="info" showIcon />
            <Form.Item
              wrapperCol={{ offset: 4 }}
            >
              <Space>
                <Button onClick={() => this.props.history.goBack()}>取消</Button>
                <Button htmlType="submit" type="primary" loading={saveFormBtn}>保存</Button>
              </Space>
            </Form.Item>
          </Form>
          <Modal title="选择频道" visible={isModalOpen} onOk={isModalOpen} width={1200}
            onCancel={this.cancelChannel}
            footer={[
              <Button key="back" onClick={this.cancelChannel}>取消</Button>,
              <Button key="submit" type="primary" onClick={() => { this.saveChannel() }} disabled={selectedRowKeys.length !== 0 ? false : true} >保存</Button>
            ]}>
            <TheTable
              scroll={{ x: "max-content", y: "40vh" }}
              columns={columns}
              dataSource={dataSource}
              rowKey={'channelId'}
              rowSelection={rowSelection}
            />
            <ThePagination
              pageNo={pageData.pageNo}
              pageSize={pageData.pageSize}
              total={total}
              pageChange={this.pageChange}
            />
          </Modal>
        </div >
      </div >
    )
  }
}
